package com.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.entity.UserEntity;
import com.service.UserService;
import com.service.serviceImpl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/app/loginServlet")
public class loginServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private Map<String, Object> responseMap = new HashMap<String, Object>();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        BufferedReader reader = request.getReader();
        String params = reader.readLine();
        HttpSession session = request.getSession();
        String code = session.getAttribute("code").toString();
        JSONObject jsonObject = JSON.parseObject(params);
        String check = jsonObject.get("check").toString();
        if (!code.equalsIgnoreCase(check)) {
            responseMap.put("flag", false);
            responseMap.put("msg", "验证码错误");
            String JSONMap = JSON.toJSONString(responseMap);
            response.getWriter().write(JSONMap);
            session.removeAttribute("code");
            return;
        }
        UserEntity userEntity = JSON.parseObject(params, UserEntity.class);
        String userName = userEntity.getUserName();
        String password = userEntity.getPassword();
        UserEntity selectUser = userService.selectUser(userName, password);
        if (selectUser == null) {
            responseMap.put("flag", false);
            responseMap.put("msg", "用户不存在");
            session.removeAttribute("code");
            String JSONMap = JSON.toJSONString(responseMap);
            response.getWriter().write(JSONMap);
        } else {
            responseMap.put("flag", true);
            responseMap.put("msg", "登录成功");
            session.removeAttribute("code");
            session.setAttribute("userId", selectUser.getId());
            String JSONMap = JSON.toJSONString(responseMap);
            response.getWriter().write(JSONMap);
        }

    }
}
